package com.nuoniu.sibanyun.controller.personal;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nuoniu.sibanyun.common.exception.NuoNiuException;
import com.nuoniu.sibanyun.common.lang.StringUtils;
import com.nuoniu.sibanyun.common.result.HttpResult;
import com.nuoniu.sibanyun.config.YmlConfig;
import com.nuoniu.sibanyun.entity.SysCompany;
import com.nuoniu.sibanyun.entity.SysEmployee;
import com.nuoniu.sibanyun.entity.SysUser;
import com.nuoniu.sibanyun.entity.crm.CommissionRecord;
import com.nuoniu.sibanyun.entity.crm.CrmWebConfig;
import com.nuoniu.sibanyun.entity.crm.WithdrawalRecord;
import com.nuoniu.sibanyun.service.ISysCompanyService;
//import com.nuoniu.sibanyun.service.ISysEmployeeService;
import com.nuoniu.sibanyun.service.ISysUserService;
import com.nuoniu.sibanyun.service.crm.*;
import com.nuoniu.sibanyun.service.redis.RedisService;
import com.nuoniu.sibanyun.userThread.UserInfo;
import com.nuoniu.sibanyun.userThread.UserThreadLocal;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 个人中心
 * @auther 小啊刚
 * @date 2020/7/14
 */
@RestController
@RequestMapping("/personal")
@Api(value="个人中心 ",tags={"个人中心"})
public class UserInfoController {

    @Autowired
    private ISysUserService userService;
    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;
    @Autowired
    private ICommissionRecordService commissionRecordService;
    @Autowired
    private ICrmWebConfigService webConfigService;
    @Autowired
    private IWithdrawalRecordService withdrawalRecordService;
    @Autowired
    private ICrmCustomerService crmCustomerService;
    @Autowired
    private IApprovalProcessService processService;
    @Autowired
    private RedisService redisService;
//    @Autowired
//    private ISysEmployeeService employeeService;
    @Autowired
    private ISysCompanyService companyService;

    /**
     * 获取用户基本信息
     * @author 小啊刚
     * @date 2020/7/14
     */
    @GetMapping("getUserInfo")
    @ApiOperation(value = "获取用户基本信息",tags = "APP_个人中心")
    public HttpResult<UserInfo> userInfo() {
        UserInfo userInfo = UserThreadLocal.get();
        SysUser user = userService.getById(userInfo.getUserId());
        if(user != null) {
            SysUser employee = userService.getByUserId(user.getId());
            if(employee != null) {
                if (employee.getOfficeId()!=null)
                {userInfo.setOfficeId(employee.getOfficeId().intValue());}
                userInfo.setOfficeName(employee.getOfficeName());
            }

            userInfo.setRealName(user.getRealName());
            userInfo.setEmail(user.getEmail());
            userInfo.setMobile(user.getMobile());
            userInfo.setSign(user.getSign());
            userInfo.setSex(user.getSex() ? 1 : 0);
            userInfo.setAvatar(user.getAvatar());
            userInfo.setLastLoginDate(user.getLastLoginDate());
            userInfo.setTotalCommission(user.getTotalCommission());
            userInfo.setWithdrawalCommission(user.getWithdrawalCommission());
            userInfo.setBankAccount(user.getBankAccount());
            userInfo.setBankName(user.getBankName());

            if(userInfo.getCompanyId() != null) {

            }
        }
        return HttpResult.ok(userInfo);
    }

    /**
     * 保存个人信息
     * @author 小啊刚
     * @date 2020/7/15
     */
    @PostMapping("save")
    @ApiOperation(value = "保存个人信息（id(必填)、姓名（必填）、邮箱（必填、手机（可选））",tags = "APP_个人中心")
    public HttpResult save(@RequestBody SysUser user) {
        UserInfo userInfo = UserThreadLocal.get();

        if(StringUtils.isNotBlank(user.getEmail())) {
            SysUser sysUser = userService.checkUserEmail(user);
            if(sysUser != null) {
                throw new NuoNiuException("邮箱已存在");
            }
        }

        if(userInfo.getRealName() != null && !userInfo.getRealName().equals(user.getRealName())) {
            //修改客户数据
            crmCustomerService.updateUserRealName(user.getId(), user.getRealName());
            //修改审核人
            processService.updateUserName(user.getId(), user.getRealName());
            SysUser employee = userService.getByUserId(user.getId());
            if(employee != null) {
                employee.setRealName(user.getRealName());
                userService.updateById(employee);
            }
        }
        userService.updateById(user);
        return HttpResult.ok();
    }

    /**
     * 校验密码
     * @author 小啊刚
     * @date 2020/7/15
     */
    @GetMapping("checkPwd")
    @ApiOperation(value = "校验密码",tags = "APP_个人中心")
    public HttpResult checkPwd(String pwd) {
        UserInfo userInfo =  UserThreadLocal.get();
        SysUser user = userService.getById(userInfo.getUserId());
        if(bCryptPasswordEncoder.matches(pwd, user.getPassword())) {
            return HttpResult.ok();
        }
        throw new NuoNiuException("校验失败");
    }

    /**
     * 修改用户密码
     * @author 小啊刚
     * @date 2020/7/15
     */
    @PostMapping("savePwd")
    @ApiOperation(value = "修改用户密码 oldPwd:旧密码，pwd：新密码",tags = "APP_个人中心")
    public HttpResult savePwd(@RequestBody Map<String, String> data) {
        UserInfo userInfo =  UserThreadLocal.get();
        SysUser user = userService.getById(userInfo.getUserId());
        if(bCryptPasswordEncoder.matches(data.get("oldPwd"), user.getPassword())) {
            user.setPassword(bCryptPasswordEncoder.encode(data.get("pwd")));
            userService.updateById(user);
            return HttpResult.ok();
        }
        throw new NuoNiuException("原始密码不正确");
    }

    /**
     * 修改登录手机号
     * @author 小啊刚
     * @date 2020-08-06
     */
    @PostMapping("updateLoginPhone")
    @ApiOperation(value = "修改登录手机号,loginPhone:登录手机号，vCode：短信验证码",tags = "APP_个人中心")
    public HttpResult updateLoginPhone(@RequestBody Map<String, String> data) {
        String userPhone = data.get("loginPhone");
        if(StringUtils.isEmpty(userPhone)) {
            throw new NuoNiuException("手机号不能为空");
        }
        if(StringUtils.isEmpty(data.get("vCode"))) {
            throw new NuoNiuException("验证码不能为空");
        }

        String smsCode = redisService.get("sms_" + userPhone).toString();
        if(!smsCode.equals(data.get("vCode"))) {
            throw new NuoNiuException("验证码不正确");
        }

        SysUser sysUser = userService.getUserByPhone(userPhone);
        if(sysUser != null) {
            throw new NuoNiuException("手机号已注册");
        }

        UserInfo userInfo = UserThreadLocal.get();
        sysUser = new SysUser();
        sysUser.setId(userInfo.getUserId().longValue());
        sysUser.setUserName(userPhone);
        userService.updateById(sysUser);
        return HttpResult.ok();
    }

    /**
     * 我的分享基本信息
     * @author 小啊刚
     * @date 2020-07-28
     */
    @GetMapping("getShareInfo")
    @ApiOperation(value = "我的分享基本信息{registerUrl:分享地址,extensionMethod:推广方法,commissionRules:佣金规则,title:分享标题,shareRemark:分享描述}",tags = "APP_个人中心")
    public HttpResult getShareInfo() {
        Map<String, String> data = new HashMap<>();
        UserInfo userInfo = UserThreadLocal.get();
        SysUser user = userService.getById(userInfo.getUserId().longValue());
        String registerUrl = YmlConfig.REGISTER_URL + "?share=" + user.getUserName() + "&code=" + user.getUserCode();
        CrmWebConfig webConfig = webConfigService.getById(1);
        data.put("registerUrl", registerUrl);
        data.put("shareImgUrl", webConfig.getShareImg());
        data.put("extensionMethod", webConfig.getExtensionMethod());
        data.put("commissionRules", webConfig.getCommissionRules());
        data.put("title", webConfig.getShareTitle());
        data.put("shareRemark", webConfig.getShareRemark());
        return HttpResult.ok("获取成功", data);
    }

    /**
     * 我的下级个人会员
     * @author 小啊刚
     * @date 2020-07-28
     */
    @GetMapping("getShareUserList")
    @ApiOperation(value = "查询我的下级个人会员。租户名称（选填）：companyName,用户姓名（选填）：realName",tags = "APP_个人中心")
    public HttpResult<Page<SysUser>> getShareUserList(Page page, SysUser user) {
        return HttpResult.ok(userService.getShareUserList(page, user));
    }

    @ApiOperation("获取我的所有推客列表")
    @GetMapping("getShareUserAll")
    public HttpResult getShareUserAll() {
        return HttpResult.ok(userService.getShareUserAll());
    }

    /**
     * 我的下级公司会员
     * @author 小啊刚
     * @date 2020-07-28
     */
    @GetMapping("getShareCrmList")
    @ApiOperation(value = "查询我的下级公司会员。租户名称（选填）：companyName,用户姓名（选填）：realName",tags = "APP_个人中心")
    public HttpResult getShareCrmList(Page page, SysCompany company) {
        return HttpResult.ok(userService.getShareCrmList(page, company));
    }

    /**
     * 获取我的佣金记录
     * @author 小啊刚
     * @date 2020-07-29
     */
    @GetMapping("getCommissionRecord")
    @ApiOperation(value = "获取我的佣金记录（只传分页信息: current,size）",tags = "APP_个人中心")
    public HttpResult getCommissionRecord(Page page, CommissionRecord record) {
        Page<CommissionRecord> commissionRecordPage = commissionRecordService.getCommissionRecord(page, record);
        return HttpResult.ok(commissionRecordPage);
    }

    /**
     * 获取我的提现记录
     * @author 小啊刚
     * @date 2020-07-30
     */
    @GetMapping("getWithdrawalRecord")
    @ApiOperation(value = "获取我的提现记录（status(选填):0:已提现 1:待审核 2:审核中 3:审核驳回 4:待打款 5:待到账;user_name（选填）:提现用户登录账号）",tags = "APP_个人中心")
    public HttpResult getWithdrawalRecord(Page page, WithdrawalRecord record) {
        Page<WithdrawalRecord> withdrawalRecordPage = withdrawalRecordService.getWithdrawalRecord(page, record);
        return HttpResult.ok(withdrawalRecordPage);
    }

    /**
     * 个人提现
     * @author 小啊刚
     * @date 2020-07-29
     */
    @GetMapping("withdrawalCommission")
    public HttpResult withdrawalCommission(Integer amount) {
        CrmWebConfig config = webConfigService.getById(1);
        if(amount < config.getWithdrawalLimit()) {
            throw new NuoNiuException("提现金额不能小于" + config.getWithdrawalLimit());
        }
        return withdrawalRecordService.withdrawalCommission(amount);
    }

    /**
     * 修改提现状态
     * @author 小啊刚
     * @date 2020-07-30
     */
    @PostMapping("updateWithdrawalStatus")
    public HttpResult updateWithdrawalStatus(@RequestBody WithdrawalRecord record) {
        withdrawalRecordService.updateById(record);
        return HttpResult.ok();
    }

    /**
     * 升级为单位用户
     * @author 小啊刚
     * @date 2020-09-30
     */
    @ApiOperation("升级为单位用户")
    @GetMapping("updateUserType")
    public HttpResult updateUserType(String companyName) {
        if(StringUtils.isBlank(companyName)) {
            throw new NuoNiuException("单位名称不能为空");
        }

        UserInfo userInfo = UserThreadLocal.get();
        if(userInfo.getCompanyId() != null) {
            throw new NuoNiuException("已是单位用户");
        }

        SysCompany company = companyService.getByName(companyName);
        if(company != null) {
            throw new NuoNiuException("单位名称已存在");
        }

        userInfo.setCompanyName(companyName);
        userService.updateUserType(userInfo);
        return HttpResult.ok("修改成功");
    }

    /**
     * 单位转成个人用户
     * @author 小啊刚
     * @date 2022-06-01
     */
    @ApiOperation("单位转成个人用户")
    @GetMapping("updateCompanyType")
    public HttpResult updateCompanyType() {
        userService.updateCompanyType();
        return HttpResult.ok();
    }

    @ApiOperation("离职")
    @GetMapping("quit")
    public HttpResult quit(Integer userId) {
        userService.quit(userId);
        return HttpResult.ok();
    }
}
